package com.smarthome.worker;

import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smarthome.core.workingmonitor.WorkerService;

/**
 * <B>重新载入任务</B> TODO <br />
 * @author KongXiangyu
 */
@Controller
@RequestMapping(value = "/worker")
public class WorkerController {

    public final Logger logger = Logger.getLogger(this.getClass());
    @Resource
    private WorkerService workerService;
    @Resource
    private WorkerManager workerManager;

    @RequestMapping(value = "/reload", method = { RequestMethod.GET })
    @ResponseBody
    public void reload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("WorkerController-reload...");
        response.setContentType("text/javascript;charset=UTF-8");
        PrintWriter out = response.getWriter();
        workerManager.loadJobs();
        List<WorkerJob> jobs = workerManager.getAllJob();
        logger.info("finished!.....current-workers:" + (null == jobs ? 0 : jobs.size()));
        out.write("finished!.....current-workers:" + (null == jobs ? 0 : jobs.size()));
        out.flush();
    }

    @RequestMapping(value = "/stop", method = { RequestMethod.GET })
    @ResponseBody
    public void stop(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("WorkerController-reload...");
        response.setContentType("text/javascript;charset=UTF-8");
        PrintWriter out = response.getWriter();
        workerManager.removeAllJobs();
        List<WorkerJob> jobs = workerManager.getAllJob();
        logger.info("finished!.....current-workers:" + (null == jobs ? 0 : jobs.size()));
        out.write("finished!.....current-workers:" + (null == jobs ? 0 : jobs.size()));
        out.flush();
    }
}
